//
//  QLMSerRouteMapVC.m
//  Xiaomakuaixiu
//
//  Created by 龚碧容 on 2017/11/23.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "QLMSerRouteMapVC.h"

@interface QLMSerRouteMapVC ()<BMKMapViewDelegate,BMKRouteSearchDelegate>{
    BMKMapView *_mapView;
    BMKRouteSearch *_routeSearch;
    BMKPolyline *routeLine;
}

@end

@implementation QLMSerRouteMapVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title=@"地图详情";
    
    _mapView=[[BMKMapView alloc] initWithFrame:CGRectMake(0,0,kScreen_width,kScreen_height-IOS11_OR_LATER_SPACE(34)-QLM_StatusBarAndNavigationBarHeight)];
    _mapView.mapType=BMKMapTypeStandard;
    [self.view addSubview:_mapView];
    _routeSearch = [[BMKRouteSearch alloc] init];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _mapView.delegate=self;
    _routeSearch.delegate = self;
    
    if (_arriveBool) {
        [self configureRoutes:_locationArray];
    }else{
        [self _startSearchRouteLine];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    _routeSearch.delegate = nil; // 不用时，置nil
    _mapView.delegate=nil;
}

- (void)dealloc {
    if (_routeSearch != nil) {
        _routeSearch = nil;
    }
    if (_mapView) {
        _mapView = nil;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation{
    
    if ([annotation isKindOfClass:[RouteAnnotation class]]) {
        return [(RouteAnnotation*)annotation getRouteAnnotationView:view];
    }else{
        // 生成重用标示identifier
        NSString *AnnotationViewID = @"xidanMark";
        // 检查是否有重用的缓存
        BMKAnnotationView* annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        // 缓存没有命中，自己构造一个，一般首次添加annotation代码会运行到此处
        if (annotationView == nil) {
            annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
            ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorGreen;
            // 设置重天上掉下的效果(annotation)
            ((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
        }
        // 设置位置
        annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
        annotationView.annotation = annotation;
        // 单击弹出泡泡，弹出泡泡前提annotation必须实现title属性
        annotationView.canShowCallout = YES;
        // 设置是否可以拖拽
        annotationView.draggable = NO;
        return annotationView;
    }
    
    return nil;
}

- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay{
    
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.fillColor = [[UIColor alloc] initWithRed:0 green:1 blue:1 alpha:1];
        polylineView.strokeColor = [UIColor greenColor];
        polylineView.lineWidth = 3.0;
        return polylineView;
    }
    return nil;
}

- (BMKPlanNode *)SetUpStartPlanNode:(NSDictionary *)dic{
    BMKPlanNode *start = [[BMKPlanNode alloc]init];
    start.pt = (CLLocationCoordinate2D){[dic[@"latitu"] doubleValue], [dic[@"longtitu"] doubleValue]};;
    return start;
}

#pragma mark - BMKMapview delegate
- (void)_startSearchRouteLine{
    NSDictionary *startdic=[NSDictionary dictionaryWithObjectsAndKeys:_astartdic[@"lat"],@"latitu",_astartdic[@"long"],@"longtitu", nil];
    
    BMKDrivingRoutePlanOption *drivingRouteSearchOption = [[BMKDrivingRoutePlanOption alloc]init];
    drivingRouteSearchOption.from = [self SetUpStartPlanNode:startdic];
    drivingRouteSearchOption.to = [self SetUpStartPlanNode:_geoEndDic];
    drivingRouteSearchOption.drivingRequestTrafficType = BMK_DRIVING_REQUEST_TRAFFICE_TYPE_NONE;//不获取路况信息
    BOOL flag = [_routeSearch drivingSearch:drivingRouteSearchOption];
    if(flag){
        NSLog(@"car检索发送成功");
    }else{
        NSLog(@"car检索发送失败");
    }
}

- (void)onGetDrivingRouteResult:(BMKRouteSearch*)searcher result:(BMKDrivingRouteResult*)result errorCode:(BMKSearchErrorCode)error {
    
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    
    if (error == BMK_SEARCH_NO_ERROR) {
        
        BMKDrivingRouteLine* plan = (BMKDrivingRouteLine*)[result.routes objectAtIndex:0];
        // 计算路线方案中的路段数目
        NSInteger size = [plan.steps count];
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:i];
            if(i==0){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.starting.location;
                item.title = @"起点";
                item.type = 0;
                [_mapView addAnnotation:item]; // 添加起点标注
            }
            if(i==size-1){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.terminal.location;
                item.title = @"终点";
                item.type = 1;
                [_mapView addAnnotation:item]; // 添加起点标注
            }
            //添加annotation节点
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = transitStep.entrace.location;
            item.title = transitStep.entraceInstruction;
            item.degree = transitStep.direction * 30;
            item.type = 4;
            [_mapView addAnnotation:item];
            
            //轨迹点总数累计
            planPointCounts += transitStep.pointsCount;
        }
        // 添加途经点
        if (plan.wayPoints) {
            for (BMKPlanNode* tempNode in plan.wayPoints) {
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item = [[RouteAnnotation alloc]init];
                item.coordinate = tempNode.pt;
                item.type = 5;
                item.title = tempNode.name;
                [_mapView addAnnotation:item];
            }
        }
        //轨迹点
        BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
        }
        // 通过points构建BMKPolyline
        BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        [_mapView addOverlay:polyLine]; // 添加路线overlay
        delete []temppoints;
        [self mapViewFitPolyLine:polyLine];
    }
}

//根据polyline设置地图范围
- (void)mapViewFitPolyLine:(BMKPolyline *) polyLine {
    CGFloat leftTopX, leftTopY, rightBottomX, rightBottomY;
    if (polyLine.pointCount < 1) {
        return;
    }
    BMKMapPoint pt = polyLine.points[0];
    // 左上角顶点
    leftTopX = pt.x;
    leftTopY = pt.y;
    // 右下角顶点
    rightBottomX = pt.x;
    rightBottomY = pt.y;
    for (int i = 1; i < polyLine.pointCount; i++) {
        BMKMapPoint pt = polyLine.points[i];
        leftTopX = pt.x < leftTopX ? pt.x : leftTopX;
        leftTopY = pt.y < leftTopY ? pt.y : leftTopY;
        rightBottomX = pt.x > rightBottomX ? pt.x : rightBottomX;
        rightBottomY = pt.y > rightBottomY ? pt.y : rightBottomY;
    }
    BMKMapRect rect;
    rect.origin = BMKMapPointMake(leftTopX, leftTopY);
    rect.size = BMKMapSizeMake(rightBottomX - leftTopX, rightBottomY - leftTopY);
    UIEdgeInsets padding = UIEdgeInsetsMake(30, 0, 100, 0);
    BMKMapRect fitRect = [_mapView mapRectThatFits:rect edgePadding:padding];
    [_mapView setVisibleMapRect:fitRect];
}

- (void)configureRoutes:(NSArray *)locationPoint{
    // 1、分配内存空间给存储经过点的数组
    BMKMapPoint* pointArray = (BMKMapPoint *)malloc(sizeof(CLLocationCoordinate2D) * locationPoint.count);
    // 2、创建坐标点并添加到数组中
    NSInteger idxCount=locationPoint.count;
    if (locationPoint.count>300) {
        idxCount=300;
    }
    
    NSInteger size = idxCount;
    for (int i = 0; i < size; i++) {
        
        CLLocationDegrees latitude=[[locationPoint[i] objectForKey:@"latitude"] doubleValue];
        CLLocationDegrees longitude=[[locationPoint[i] objectForKey:@"longitude"] doubleValue];
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);
        
        BMKMapPoint point = BMKMapPointForCoordinate(coordinate);
        if (i==0) {
            _mapView.centerCoordinate = coordinate;
        }
        pointArray[i] = point;
        
        if(i==0){
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = coordinate;
            item.title = @"起点";
            item.type = 0;
            [_mapView addAnnotation:item]; // 添加起点标注
        }
        
        if(i==size-1){
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = coordinate;
            item.title = @"终点";
            item.type = 1;
            [_mapView addAnnotation:item]; // 添加起点标注
        }
        
        //添加annotation节点
        RouteAnnotation* item = [[RouteAnnotation alloc]init];
        item.coordinate = coordinate;
        item.title = @"";
        item.type = 4;
        [_mapView addAnnotation:item];
        
        RouteAnnotation* tmpItem = [[RouteAnnotation alloc]init];
        tmpItem.coordinate = coordinate;
        tmpItem.type = 5;
        tmpItem.title = @"";
        [_mapView addAnnotation:item];
    }
    
    // 3、防止重复绘制
    if (routeLine) {
        //在地图上移除已有的坐标点
        [_mapView removeOverlay:routeLine];
    }
    // 4、画线
    routeLine = [BMKPolyline polylineWithPoints:pointArray count:locationPoint.count];
    // 5、将折线(覆盖)添加到地图
    if (nil != routeLine) {
        [_mapView addOverlay:routeLine];
    }
    [self mapViewFitPolyLine:routeLine];
    free(pointArray);
}

@end
